<template>
  <view class="orderConfim">
    <view class="address" @tap="getAddress()">
      <view class="addressLeft">
        <view class="addressTitle">
          <text class="at-icon at-icon-map-pin map" />
          <text class="name">
            {{ userinfo || "选择收货地址" }}
          </text>
        </view>
        <view class="addressDetails">{{
          address || "从微信地址选择或添加"
        }}</view>
      </view>
      <view class="addressRight">
        <view class="addressRightIcon">
          <view class="at-icon at-icon-chevron-right arrow" />
        </view>
      </view>
    </view>
    <view class="orderListBody">
      <OrderList :canCountChange="false" :list="orderProducts" />
      <view class="bodyFooter">
        <view class="bodyFooterItem">
          <view class="grayLabel">商品数量：</view>
          <view>{{ orderProducts.length }}</view>
        </view>
        <view class="bodyFooterItem">
          <view class="grayLabel">运费：</view>
          <view>{{ userinfo ? 0 : "请先选择收货地址" }}</view>
        </view>
        <view class="bodyFooterItem">
          <view>商品总金额：</view>
          <view class="price">{{ totalPriceString }}</view>
        </view>
      </view>
    </view>
    <!-- <view v-for="item in orderProducts" :key="item.id">
      <image class="image" :src="getMainImageUrl(item.product)" />
      <view>名称{{ item.product.name }}</view>
      <text v-if="item.price.points">
        <text class="number">{{ item.price.points }}</text>
        积分
      </text>
      <text v-if="item.price.money"
        >￥<text class="number">{{ moneyFormat(item.price.money) }}</text>
      </text>
      <text>数量：{{ item.count }}</text>
    </view> -->
    <view class="orderFooter">
      <view class="footerItem left" />
      <view class="footerItem" @tap="confirm">
        <view class="bottomButton">立即支付</view>
      </view>
    </view>
    <AtToast
      text="请先选择地址"
      status="error"
      :hasMask="true"
      :is-opened="isOpen"
      :duration="1000"
      :on-close="closeToast"
    />
    <HomeFab />
  </view>
</template>

<script lang="ts">
import "./index.less";
import Taro from "@tarojs/taro";
import { AtToast } from "taro-ui-vue";
import {
  pointsRedeem,
  getMainImageUrl,
  moneyFormat,
  confirmOrder,
  pay,
} from "../../../../services/products-service";
import HomeFab from "../../../../common-components/fab/index.vue";
import OrderList from "../../components/orderList/index.vue";

export default {
  components: {
    OrderList,
    HomeFab,
    AtToast,
  },
  data() {
    return { address: "", isOpen: false, userName: "", telNumber: "" };
  },
  computed: {
    // address() {
    //   return this.$store.state.products.address;
    // },
    userinfo() {
      const { userName, telNumber } = this;
      if (userName && telNumber) {
        return `${userName} ${telNumber}`;
      }
      return "";
    },
    orderProducts() {
      return this.$store.state.products.orderProducts;
    },
    totalPrice() {
      const money = this.orderProducts.reduce(
        (a, b) => a + b.price.money * b.count,
        0
      );
      const points = this.orderProducts.reduce(
        (a, b) => a + b.price.points * b.count,
        0
      );
      return { money, points };
    },
    totalPriceString() {
      const { money, points } = this.totalPrice;
      return money ? `￥${moneyFormat(money)}` : `${points}积分`;
    },
    isPoints() {
      return !!this.orderProducts.reduce((a, b) => a + b.price.points, 0);
    },
  },
  methods: {
    getMainImageUrl,
    moneyFormat,
    async getAddress() {
      const x = await Taro.chooseAddress();
      const {
        errMsg,
        userName,
        telNumber,
        provinceName,
        cityName,
        countyName,
        detailInfo,
        postalCode,
      } = x;
      if (errMsg === "chooseAddress:ok") {
        this.address = `${provinceName}${cityName}${countyName}${detailInfo}`;
        this.userName = userName;
        this.telNumber = telNumber;
        this.postalCode = postalCode;
      } else {
        console.log(errMsg);
      }
      return x;
    },
    closeToast() {
      this.isOpen = false;
    },
    openToast() {
      this.isOpen = true;
    },
    goToMyOrder() {
      Taro.navigateTo({ url: "/pages/sales/order/my-order/index" });
    },
    goToResult(result) {
      Taro.navigateTo({ url: `/pages/sales/payresult/index?result=${result}` });
    },
    async confirm() {
      console.log("confirm", this);
      const { address, userName, telNumber, postalCode } = this;
      if (!(address && userName && telNumber)) {
        this.openToast();
        console.log("请先选择地址");
        return;
      }
      if (this.isPoints) {
        try {
          const x = await pointsRedeem({
            consignee: {
              address,
              name: userName,
              phone: telNumber,
              postalCode: postalCode,
            },
            products: this.orderProducts.map((item) => ({
              ...item,
              product: undefined,
            })),
            remark: "",
            totalPrice: this.totalPrice,
          });
          console.log("point order result", x);
          if (x.statusCode === 200) {
            this.$store.commit("clearSalesOrder");
            this.goToResult("success");
          } else {
            this.goToResult();
          }
        } catch (err) {
          this.goToResult();
        }
      } else {
        try {
          const x = await confirmOrder({
            consignee: {
              address,
              name: userName,
              phone: telNumber,
              postalCode: postalCode,
            },
            products: this.orderProducts.map((item) => ({
              ...item,
              product: undefined,
            })),
            remark: "",
            totalPrice: this.totalPrice,
          });
          console.log("confirm buy", x);
          if (x.statusCode === 200) {
            const payData = await pay(x.data.data.id);
            return Taro.requestPayment({
              ...payData,
              success: (data) => {
                console.log("pay success", data);
                this.$store.commit("clearSalesOrder");
                this.goToResult("success");
              },
              fail: (error) => {
                console.log("pay fail", error);
                this.goToResult();
              },
            });
          }
          return this.goToResult();
        } catch {
          return this.goToResult();
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~taro-ui-vue/dist/style/components/toast.scss";
@import "~taro-ui-vue/dist/style/components/icon.scss";
</style>